package com.kafka.kafkademo.partition;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

public class MyPartition implements Partitioner {
    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
       List<PartitionInfo> partitionInfos =  cluster.partitionsForTopic(topic);
       int partitionNum = 0;
       if(key == null){
           partitionNum = new Random().nextInt(partitionInfos.size());
       }else {
           partitionNum = Math.abs(key.hashCode())%partitionInfos.size();
       }
       System.err.println("key: " + key + " value:" +value + "partition:" + partitionNum);
       return partitionNum;
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> map) {

    }
}
